package com.madev.isellcrazyitems;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import com.madev.isellcrazyitems.entity.Product;
import com.madev.isellcrazyitems.entity.Sales;
import com.madev.isellcrazyitems.entity.SalesOrder;
import com.madev.isellcrazyitems.entity.User;
import com.madev.isellcrazyitems.handler.JSONController;
import com.madev.isellcrazyitems.handler.DatabaseHandler;
import com.madev.sales.R;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;

public class History extends Activity {
	//private Product product = new Product();
	private User customer = new User();
	private Sales sales = new Sales();
	private SalesOrder salesOrder = new SalesOrder();
	private TableLayout historyTable;
	private ArrayList<Integer> itemArr, qtyArr;
	private ArrayList<Product> prodArr = new ArrayList<Product>();
    private JSONController jController = new JSONController();
    private ArrayList<Integer> posArr = new ArrayList<Integer>();
    private final DecimalFormat df = new DecimalFormat("#.00");
    private static String customer_sales_url = "http://unifiq.5kportal.com/retrieve_customer_sales.php";
    private static String customer_sales_order_url = "http://unifiq.5kportal.com/retrieve_customer_sales_order.php";
    private static final String TAG_SUCCESS = "success", TAG_ID = "id", TAG_SALES_ORDER_QUANTITY = "salesOrderQuantity", TAG_SALES_CUSTOMER_ID = "salesCustomerID", TAG_SALES_ORDER_PRODUCT_ID = "salesOrderProductID", TAG_SALES_PURCHASE_DATE = "salesPurchaseDate", TAG_SALES = "sales", TAG_SALES_ORDER = "sales_order", TAG_SALES_ID = "salesID", TAG_SALES_ORDER_ID = "salesOrderID";
    private JSONArray salesJArr = null, salesOrderJArr = null;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.history_layout);
        
        Bundle bundle = getIntent().getExtras();
        itemArr = bundle.getIntegerArrayList("itemArr");
        qtyArr = bundle.getIntegerArrayList("qtyArr");
        DatabaseHandler productHandler = new DatabaseHandler(getApplicationContext());
        prodArr = productHandler.getProducts();
        productHandler.close();
        customer = (User) bundle.getSerializable("customer");
        historyTable = (TableLayout) findViewById(R.id.history_table);

        //retrieving order history from local database
        DatabaseHandler salesHandler = new DatabaseHandler(getApplicationContext());
        salesHandler.getWritableDatabase();
        sales = salesHandler.retrieveSales(customer.getUserId());
        salesHandler.close();
        
        DatabaseHandler salesOrderHandler = new DatabaseHandler(getApplicationContext());
        salesOrderHandler.getWritableDatabase();
        
        for (int q = 0; q < sales.getSalesID().size(); q++){
        	SalesOrder so = new SalesOrder();
	        so = salesOrderHandler.retrieveSalesOrder(sales.getSalesID().get(q));
	        
	        for (int w = 0; w < so.getSalesOrderProductID().size(); w++){
	        	salesOrder.setSalesOrderID(so.getSalesOrderID().get(w));
	        	salesOrder.setSalesOrderProductID(so.getSalesOrderProductID().get(w));
	        	salesOrder.setSalesQuantity(so.getSalesQuantity().get(w));
	        }
        }
        
        salesOrderHandler.close();
        
        // retrieving order history from online database
        /*List<NameValuePair> salesParams = new ArrayList<NameValuePair>();
        salesParams.add(new BasicNameValuePair(TAG_SALES_CUSTOMER_ID, String.valueOf(customer.getId().get(0))));

        JSONObject salesObj = jController.makeHttpRequest(customer_sales_url, "GET", salesParams);
           
	    try {
	        int success = salesObj.getInt(TAG_SUCCESS);

	        if (success == 1) {
	            salesJArr = salesObj.getJSONArray(TAG_SALES);

	            for (int a = 0; a < salesJArr.length(); a++) {
	                JSONObject jObject = salesJArr.getJSONObject(a);
	                
	                sales.setSalesID(jObject.getInt(TAG_SALES_ID));
	                sales.setSalesCustomerID(jObject.getInt(TAG_SALES_CUSTOMER_ID));
	                
	                Date purchaseDate = null;
	                
					try {
						purchaseDate = stringToDate(jObject.getString(TAG_SALES_PURCHASE_DATE));
					} catch (ParseException e) {
						// TODO Auto-generated catch blo-ck
						e.printStackTrace();
					} 
	
					sales.setSalesPurchaseDate(purchaseDate);
	            }
	        } else {
	        }
	    } catch (JSONException e) {
	        e.printStackTrace();
	    }
	    
	    for (int i = 0; i < sales.getSalesID().size(); i++){
	        List<NameValuePair> salesOrderParams = new ArrayList<NameValuePair>();
	        salesOrderParams.add(new BasicNameValuePair(TAG_SALES_ORDER_ID, String.valueOf(sales.getSalesID().get(i))));
	
	        JSONObject salesOrderObj = jController.makeHttpRequest(customer_sales_order_url, "GET", salesOrderParams);
	           
		    try {
		        int success = salesOrderObj.getInt(TAG_SUCCESS);
	
		        if (success == 1) {
		            salesOrderJArr = salesOrderObj.getJSONArray(TAG_SALES_ORDER);
		            
		            for (int a = 0; a < salesOrderJArr.length(); a++) {
		                JSONObject jObject = salesOrderJArr.getJSONObject(a);
		                
		                salesOrder.setSalesOrderID(jObject.getInt(TAG_SALES_ORDER_ID));
		                salesOrder.setSalesOrderProductID(jObject.getInt(TAG_SALES_ORDER_PRODUCT_ID));
		                salesOrder.setSalesQuantity(jObject.getInt(TAG_SALES_ORDER_QUANTITY));
		                
		            }
		        } else {
		        }
		    } catch (JSONException e) {
		        e.printStackTrace();
		    }
	    }
	    */
	    
        
        for (int a = 0; a < salesOrder.getSalesOrderProductID().size(); a++){
        	for (int b = 0; b < prodArr.size(); b++){
            	if (Integer.valueOf(prodArr.get(b).getProductID()).equals(salesOrder.getSalesOrderProductID().get(a))){
            		posArr.add(b);
            		break;
            	}
        	}
        }
        
        
        LayoutParams ww = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		
        if (sales.getSalesID().size() != 0){
		    for (int y = 0; y < sales.getSalesID().size(); y++){   		
			    double totalQtyPrice = 0;
			    int totalQty = 0;
			    
		    	TableRow dateTR = new TableRow(this), headerTR = new TableRow(this);
		    	TextView purchaseDateHeader = new TextView(this), purchaseDateTV = new TextView(this), totalQtyPriceTV = new TextView(this), totalQtyTV = new TextView(this), nameHeader = new TextView(this), qtyHeader = new TextView(this), unitPriceHeader = new TextView(this), qtyPriceHeader = new TextView(this);
	    		
		    	purchaseDateHeader.setLayoutParams(ww);
		    	purchaseDateHeader.setPadding(5, 5, 5, 5);
		    	purchaseDateHeader.setTypeface(null, Typeface.BOLD);
		    	purchaseDateHeader.setText("Purchase Date");
		    	
		    	LayoutParams purchaseDateParams = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		    	purchaseDateParams.span = 3;
		    	
		    	purchaseDateTV.setLayoutParams(purchaseDateParams);
		    	purchaseDateTV.setPadding(5, 5, 5, 5);
	    		
	    		purchaseDateTV.setText(dateToString(sales.getSalesPurchaseDate().get(y)));
	    		
	    		nameHeader.setLayoutParams(ww);
	    		nameHeader.setPadding(5, 5, 5, 5);
	    		nameHeader.setTypeface(null, Typeface.BOLD);
	    		nameHeader.setGravity(Gravity.CENTER);
	    		nameHeader.setText("Name");
	    		
	    		qtyHeader.setLayoutParams(ww);
	    		qtyHeader.setPadding(5, 5, 5, 5);
	    		qtyHeader.setTypeface(null, Typeface.BOLD);
	    		qtyHeader.setGravity(Gravity.CENTER);
	    		qtyHeader.setText("Quantity");
	    		
	    		unitPriceHeader.setLayoutParams(ww);
	    		unitPriceHeader.setPadding(5, 5, 5, 5);
	    		unitPriceHeader.setTypeface(null, Typeface.BOLD);
	    		unitPriceHeader.setGravity(Gravity.CENTER);
	    		unitPriceHeader.setText("Unit Price");
	    		
	    		qtyPriceHeader.setLayoutParams(ww);
	    		qtyPriceHeader.setPadding(5, 5, 5, 5);
	    		qtyPriceHeader.setTypeface(null, Typeface.BOLD);
	    		qtyPriceHeader.setGravity(Gravity.CENTER);
	    		qtyPriceHeader.setText("Total");
	    		
	    		dateTR.addView(purchaseDateHeader);
	    		dateTR.addView(purchaseDateTV);
	    		
	    		headerTR.addView(nameHeader);
	    		headerTR.addView(unitPriceHeader);
	    		headerTR.addView(qtyHeader);
	    		headerTR.addView(qtyPriceHeader);
	    		
	    		historyTable.addView(dateTR);
	    		historyTable.addView(headerTR);
	    		
			    for (int z = 0; z < salesOrder.getSalesOrderID().size(); z++){
			    	if (salesOrder.getSalesOrderID().get(z).equals(sales.getSalesID().get(y))){
			        	TableRow tr = new TableRow(this);
			    		TextView nameTV = new TextView(this), qtyTV = new TextView(this), unitPriceTV = new TextView(this), qtyPriceTV = new TextView(this);
			    		
			    		nameTV.setLayoutParams(ww);
			    		nameTV.setPadding(5, 5, 5, 5);
			    		nameTV.setGravity(Gravity.CENTER);
			    		
			    		qtyTV.setLayoutParams(ww);
			    		qtyTV.setPadding(5, 5, 5, 5);
			    		qtyTV.setGravity(Gravity.CENTER);
			    		
			    		unitPriceTV.setLayoutParams(ww);
			    		unitPriceTV.setPadding(5, 5, 5, 5);	    		
			    		unitPriceTV.setGravity(Gravity.CENTER);
			    		
			    		qtyPriceTV.setLayoutParams(ww);
			    		qtyPriceTV.setPadding(5, 5, 5, 5);	    		
			    		qtyPriceTV.setGravity(Gravity.CENTER);
			    		
			    		nameTV.setText(prodArr.get(posArr.get(z)).getProductName());
			    		qtyTV.setText(String.valueOf(salesOrder.getSalesQuantity().get(z)));
			    		
			    		unitPriceTV.setText("$" + prodArr.get(posArr.get(z)).getProductPrice());
			    		
			    		double qtyPrice = (Double.valueOf(prodArr.get(posArr.get(z)).getProductPrice()) * Double.valueOf(salesOrder.getSalesQuantity().get(z)));   		
			    		qtyPriceTV.setText("$" + df.format(qtyPrice));
			
			    		totalQtyPrice += qtyPrice;
			    		totalQty += salesOrder.getSalesQuantity().get(z);
			    		
			    		tr.addView(nameTV);
			    		tr.addView(unitPriceTV);
			    		tr.addView(qtyTV);
			    		tr.addView(qtyPriceTV);
			    		
			    		historyTable.addView(tr);
			    	}
			    }
			    
			        View totalBar = new View(this);
				    LayoutParams totalBarParams = new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT);
				    totalBarParams.height = 3;
				    totalBarParams.span = 4;
				    totalBar.setLayoutParams(totalBarParams);
				    totalBar.setBackgroundColor(Color.parseColor("#bdbdbd"));
				    
			    	/*TableRow totalBarTR = new TableRow(this);
			    	totalBarTR.addView(totalBar);
			    	historyTable.addView(totalBarTR);
			    	 */
			    	
				    TableRow totalTR = new TableRow(this);
			    	
			        totalQtyTV.setLayoutParams(ww);
			        totalQtyTV.setLayoutParams(new TableRow.LayoutParams(2));
			        totalQtyTV.setGravity(Gravity.CENTER);
			        totalQtyTV.setText(String.valueOf(totalQty));
			        
			        totalQtyPriceTV.setLayoutParams(ww);
			        totalQtyPriceTV.setLayoutParams(new TableRow.LayoutParams(3));
			        totalQtyPriceTV.setGravity(Gravity.CENTER);
			        totalQtyPriceTV.setText("$" + df.format(totalQtyPrice));
			                
			        totalTR.addView(totalQtyTV);
			        totalTR.addView(totalQtyPriceTV);
			        
			        historyTable.addView(totalTR);
			        
			        View horizontalBar = new View(this);
				    LayoutParams horizontalBarParams = new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT);
				    horizontalBarParams.height = 3;
				    horizontalBarParams.span = 4;
				    horizontalBar.setLayoutParams(horizontalBarParams);
				    horizontalBar.setBackgroundColor(Color.parseColor("#bdbdbd"));
				    
			    	TableRow horizontalBarTR = new TableRow(this);
			    	horizontalBarTR.addView(horizontalBar);
			    	historyTable.addView(horizontalBarTR);
			        
		    }
        }
        else{
        	TableRow tr = new TableRow(this);
        	TextView tv = new TextView(this);
        	
        	tv.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
        	tv.setPadding(5, 5, 5, 5);
        	tv.setGravity(Gravity.CENTER);
        	tv.setText("No product in history. \nProceed to purchase now! \u2191");
        	
        	tr.addView(tv);
        	historyTable.addView(tr);
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.history, menu);
        return true;
    }
 
	@SuppressLint("SimpleDateFormat")
	public Date stringToDate(String date) throws ParseException{
		return sdf.parse(date);
	}
	
	@SuppressLint("SimpleDateFormat")
	public String dateToString(Date date) {
	    return sdf.format(date);
	}
	
	@Override
	public boolean onOptionsItemSelected (MenuItem item){
		Bundle b = new Bundle();
		b.putIntegerArrayList("itemArr", itemArr);
		b.putIntegerArrayList("qtyArr", qtyArr);
		
		if (item.getItemId() == R.id.menu_purchase){
			Intent purchaseScreen = new Intent(this, Purchase.class);
			purchaseScreen.putExtras(b);
	        startActivity(purchaseScreen);
	        finish();
		}
		else if (item.getItemId() == R.id.menu_cart){
			if (itemArr.size() != 0){  
				b.putSerializable("prodArr", this.prodArr);
				b.putSerializable("customer", customer);
				Intent cartScreen = new Intent(this, Cart.class);
				cartScreen.putExtras(b);
		        startActivity(cartScreen);
		        finish();
			}
		}
		return true;
	}
}

